package sn.reader;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import sn.Net;
import sn.Neuron;
import sn.functions.LinearFunction;
import sn.layers.HiddenLayer;
import sn.layers.InputLayer;
import sn.layers.OutputLayer;

public class TextFileReader {
	
	public Net readFile(String path){
		List<String> lines = getLines(path);
		InputLayer il = createInputLayer(lines.remove(0));
		String outputLayerLine = lines.remove(lines.size()-1);
		List<HiddenLayer> hl = createHiddenLayers(lines, il.getNeuronCount());
		OutputLayer ol = createOutputLayer(outputLayerLine, hl.get(hl.size()-1).getNeuronCount());
		return new Net(il,hl,ol);
	}

	private List<HiddenLayer> createHiddenLayers(List<String> lines, int inputLayerSize) {
		List<HiddenLayer> layers = new ArrayList<HiddenLayer>();
		int previousLayerSize = inputLayerSize;
		for (String line : lines){
			List<Neuron> neurons = createNeurons(line, previousLayerSize);
			layers.add(new HiddenLayer(neurons));
			previousLayerSize = neurons.size();
		}
		return layers;
	}

	private OutputLayer createOutputLayer(String line, int previousLayerSize) {
		List<Neuron> neurons = createNeurons(line, previousLayerSize);
		return new OutputLayer(neurons);
	}

	private List<Neuron> createNeurons(String line, int weightsPerNeuron) {
		String[] weights = line.split(" ");
		List<Neuron> neurons = new ArrayList<Neuron>();
		int i = 0;
		while (i < weights.length){
			List<Double> neuronWeights = new ArrayList<Double>();
			for(int j = 0; j < weightsPerNeuron; j++){
				neuronWeights.add(Double.valueOf(weights[i]));
				i++;
			}
			neurons.add(new Neuron(new LinearFunction(), neuronWeights));
		}
		return neurons;
	}

	private InputLayer createInputLayer(String line) {
		return new InputLayer(Integer.valueOf(line));
	}

	private List<String> getLines(String path) {
		List<String> lines = new ArrayList<String>();
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)))) {
			String strLine;
			while ((strLine = reader.readLine()) != null)   {
				lines.add(strLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}

}
